import { getConfigPath } from '@mintlify/prebuild';
import detect from 'detect-port';
import Ora, { Ora as OraType } from 'ora';
import type { ArgumentsCamelCase } from 'yargs';

import { CMD_EXEC_PATH } from './constants.js';

export const checkPort = async (argv: ArgumentsCamelCase): Promise<number | undefined> => {
  const initialPort = typeof argv.port === 'number' ? argv.port : 3000;
  if (initialPort === (await detect(initialPort))) return initialPort;

  for (let port = initialPort + 1; port < initialPort + 10; port++) {
    console.log(`Port ${port - 1} is already in use. Trying ${port} instead.`);
    if (port === (await detect(port))) return port;
  }
};

export const checkNodeVersion = async () => {
  let nodeVersionString = process.version;
  if (nodeVersionString.charAt(0) === 'v') {
    nodeVersionString = nodeVersionString.slice(1);
  }
  const versionArr = nodeVersionString.split('.');
  const majorVersion = parseInt(versionArr[0]!, 10);

  if (majorVersion < 18) {
    const logger = buildLogger();
    logger.fail(
      `Mintlify requires a node version >= 18.0.0 (current version ${nodeVersionString}). Try removing the mintlify package, upgrading node, reinstalling mintlify, and running again.`
    );
    process.exit(1);
  }
};

export const buildLogger = (startText = ''): OraType => {
  const logger = Ora().start(startText);
  return logger;
};

export const checkForMintJson = async () => {
  if (await getConfigPath(CMD_EXEC_PATH)) return;
  console.error('Must be run in a directory where a mint.json file exists.');
  process.exit(1);
};
